package com.design.reactor.stretchIO._1_singleReactorSingleThread.impl.handler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 *  处理 Writer 事件
 */
public class WriterHandler extends AbstractHandler {
    static final int MAX_OUT = 1024;
    static ByteBuffer output = ByteBuffer.allocate(MAX_OUT);
    public WriterHandler()  {
    }
    public WriterHandler(Selector selector, SocketChannel socketChannel) throws IOException {
        socketChannel.configureBlocking(false);
        SelectionKey selectionKey = socketChannel.register(selector, 0);//注册一个不存在的事件
        selectionKey.attach(this);
        selectionKey.interestOps(SelectionKey.OP_WRITE);//注册写事件
        selector.wakeup();//唤醒前一个阻塞的socket
    }

    @Override
    public void handle(Selector selector, SelectableChannel channel, SelectionKey selectionKey)  {
        try{
            SocketChannel socketChannel = (SocketChannel) channel;
            output.clear();
            socketChannel.read(output);
            output.flip();
            // 写出到String
            String msg = String.valueOf( Charset.forName("UTF-8").decode(output).array() );
            System.out.println("--- WriterHandler.handle() 处理 msg : " + msg);
            process(socketChannel);
            if(socketChannel!=null) new ReaderHandler(selector,socketChannel);
        }catch (Exception e){
            selectionKey.cancel();
        }

    }

    boolean outputIsComplete() {
        // 加入实现
        return true;
    }

    void process(SocketChannel socketChannel) throws IOException {
        output.clear();
        output.put(("--- WriterHandler 服务端接收到消息，正在处理中......").getBytes());
        socketChannel.write(output);
    }
}
